<?php
	// error reporting
	error_reporting(1);
	
	// js concatenation function
	function concatenateScripts($jsFilesArray, $jsStripArray){
		// concatenate js files
		require 'class.JavaScriptPacker.php';
		for($scriptCount=0; $scriptCount<count($jsFilesArray); $scriptCount++){
			// next js lib to load
			$js = $jsFilesArray[$scriptCount];
			// exit if file does not exist
			if(!file_exists($js)){ header("HTTP/1.0 404 Not Found"); echo "404, File Not Found: " . $js; exit; }
			// read javascript file
			$script = file_get_contents($js);
			// echo info start
			echo "/// start '" . $js . "'\n\n";
			// if set true, strip whitespace from javascript, using: JavaScriptPacker($origionalScript, $encoding, $fast_decode, $special_char)
			if($jsStripArray[$scriptCount] == "true"){
				$packer = new JavaScriptPacker($script, 62, true, false);
				$packed = $packer->pack();
				// echo the stripped script
				echo $packed;
			} else{
				// echo plain script
				echo $script;
			}
			// echo info end
			echo "\n\n/// end '" . $js . "'\n";
		}
		// echo concatenated scripts
		echo $result;
	}

	// compress result to gzip
	ob_start('ob_gzhandler');

	// make content cache
	@header ('Cache-Control: private, pre-check=0, post-check=0, max-age=1080');
	@header ('Expires: ' . gmstrftime("%a, %d %b %Y %H:%M:%S GMT", time() + 1080)); //60*3
	@header ('Last-Modified: ' . gmstrftime("%a, %d %b %Y %H:%M:%S GMT", time() - 20)); //60*60*3

	// set content type
	header('Content-Type: text/javascript');
	// header("Content-Length: " . filesize($jquery));

	// path to xml file describing what js files needs to be packed
	$jsLib = "profiles/" . $_GET["lib"];
	echo "// Javascript include file: " . $jsLib . "\n";
	
	// load the jsLib xml file and create an array of js file paths
	$doc = new DOMDocument();
	$doc->load( $jsLib );
	$doc->preserveWhiteSpace = false;
	// collectors
	$jsSet = array();
	$jsStrip = array();
	// loop each 'js' node
	echo "// Scripts included:\n";
	$jsFiles = $doc->getElementsByTagName( "js" );
	foreach( $jsFiles as $js ){
		$jsPath = $js->nodeValue;
		// store path in jsSet array
		array_push($jsSet, "../" . $jsPath);
		// get 'strip' attribute value
		$strip = $js->getAttribute("strip");
		// store strip bolean in jsStrip array
		array_push($jsStrip, $strip);
		// echo script info
		echo "// \t" . $jsPath . "\n";
	}
	echo "\n\n\n";
	
	// concatenate the scripts
	concatenateScripts($jsSet, $jsStrip);
?>